//
//  WAGetStepCount.m
//  WalkiOS
//
//  Created by luqiuan on 2019/10/13.
//  Copyright © 2019 Chenmuzhou. All rights reserved.
//

#import "WAGetStepCount.h"
#import <CoreMotion/CoreMotion.h>

@implementation WAGetStepCount{
    CMPedometer *_pedometer;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _pedometer = [[CMPedometer alloc] init];
    }
    return self;
}

- (void)getHealthDataWithBlock:(CompleteBlock)completeBlock{
    
    NSInteger status = [CMPedometer authorizationStatus];
    
    if (status==CMAuthorizationStatusDenied) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请到设置里面打开隐私下面的运动与健身权限" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIApplication *application = [UIApplication sharedApplication];
            NSURL *URL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_10_0
            [application openURL:URL];
#else
            [application openURL:URL options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:^(BOOL success) {
                
                NSLog(@"%d",success);
            }];
#endif
        }]];
        [self.vc presentViewController:alert animated:YES completion:nil];
        if (completeBlock) {
            completeBlock(NO,-1, -1);
        }
    }else{
        if ([CMPedometer isStepCountingAvailable]) {
            NSDateFormatter *df = [[NSDateFormatter alloc] init];
            [df setDateFormat:@"yyyy-MM-dd"];
            NSString *yestr = [df stringFromDate:[NSDate date]];
            [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            //今天0点时间
            NSDate *d = [df dateFromString:[NSMutableString stringWithFormat:@"%@ 00:00:00",yestr]];
            //查询0点到当前时间的数据
            [_pedometer queryPedometerDataFromDate:d toDate:[NSDate dateWithTimeIntervalSinceNow:0] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
                if (error) {
                    NSLog(@"error===%@",error);
                }
                else {
                    NSLog(@"步数===%@",pedometerData.numberOfSteps);
                    NSLog(@"距离===%@",pedometerData.distance);
                    if (completeBlock) {
                        completeBlock(YES,pedometerData.numberOfSteps.integerValue, pedometerData.distance.floatValue);
                    }
                }
            }];
        } else {
            if (completeBlock) {
                completeBlock(NO,-1, -1);
            }
            NSLog(@"不可用===");
        }
    }
}
@end
